// @flow
import React, { Component } from 'react'
import styles from './PointActions.css'
import { Button, Modal, message, Popconfirm } from 'antd'
import VarModalContent from 'components/VarCompAll/VarModalContent'
import EditPoint from 'components/EditPoint'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import ReactDom from 'react-dom'

type Props = {
  data: Object,
  refreshVar: Function,
  refreshPoint: Function
}
type States = {
  visibleVariable: boolean,
  visiblePoint: boolean,
  confirmLoading: boolean,
  variableType: Array<Object>
}
class PointActions extends Component {
  props: Props
  state: States
  handleVariableOk: Function
  handleVariableCancel: Function
  showVarModal: Function
  editPoint: Function
  closeEditPoint: Function
  removeEditPoint: Function
  deletePoint: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      visibleVariable: false,
      confirmLoading: false,
      visiblePoint: false,
      variableType: []
    }
    this.handleVariableOk = this.handleVariableOk.bind(this)
    this.handleVariableCancel = this.handleVariableCancel.bind(this)
    this.showVarModal = this.showVarModal.bind(this)
    this.editPoint = this.editPoint.bind(this)
    this.closeEditPoint = this.closeEditPoint.bind(this)
    this.removeEditPoint = this.removeEditPoint.bind(this)
    this.deletePoint = this.deletePoint.bind(this)
  }

  deletePoint () {
    const { data } = this.props
    universalFetch(`${__SERVICE_API__}device/templates/monitors/points/${data.id}`, {
      method: 'DELETE'
    })
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        message.success('测点删除成功')
        this.props.refreshPoint()
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  removeEditPoint () {
    const container = this.refs.editPoint
    ReactDom.unmountComponentAtNode(container)
  }
  editPoint () {
    const container = this.refs.editPoint
    const { refreshPoint, data } = this.props
    ReactDom.render(
      <EditPoint {...{
        refreshPoint,
        data,
        removeNode: this.removeEditPoint
      }} />,
    container
    )
    this.setState({
      visiblePoint: true
    })
  }

  closeEditPoint () {
    this.setState({
      visiblePoint: false
    })
  }
  showVarModal () {
    universalFetch(`${__SERVICE_API__}device/conditions?types=variableType`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          variableType: json.result.variableType,
          visibleVariable: true
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  handleVariableOk () {
    const varForm = this.refs.varModal.getForm()
    const { data } = this.props
    varForm.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        confirmLoading: true
      })
      const values = {
        ...fieldsValue,
        variableName: fieldsValue.kmxVariableName,
        variableNameEn: fieldsValue.kmxVariableNameEn,
        variableType: fieldsValue.kmxVariableType,
        unit: fieldsValue.kmxUnit,
        monitorPointId: data.id
      }
      universalFetch(`${__SERVICE_API__}device/templates/monitors/variables`, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'POST',
        body: JSON.stringify(values)
      })
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        message.success('变量添加成功')
        this.props.refreshVar(data)
        this.setState({
          visibleVariable: false,
          confirmLoading: false
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        this.setState({
          confirmLoading: false
        })
        message.error('变量添加失败: ' + error.message)
      })
    })
  }

  handleVariableCancel () {
    this.setState({
      visibleVariable: false
    })
  }
  render () {
    const { variableType } = this.state
    const { data } = this.props
    let IsShow = 'none'
    if (data.state === 0) {
      IsShow = 'inline-block'
    }
    return (
      <div className={styles['actions']}>
        <Button size='small'
          type='primary'
          style={{ marginRight: '10px' }}
          onClick={this.showVarModal}
          >
          添加变量
        </Button>
        <label style={{ display: IsShow }}>
          <Button size='small'
            type='primary'
            style={{ marginRight: '10px' }}
            disabled={false}
            onClick={this.editPoint}
            >
            编辑
          </Button>
          <Popconfirm
            title='确定要删除此测点吗？'
            onConfirm={this.deletePoint}
            >
            <Button size='small'
              type='danger'
              style={{ marginRight: '10px' }}
              >
              删除
            </Button>
          </Popconfirm>
        </label>
        <Modal
          key='addVar'
          title='添加变量'
          visible={this.state.visibleVariable}
          onOk={this.handleVariableOk}
          confirmLoading={this.state.confirmLoading}
          onCancel={this.handleVariableCancel}
          >
          <VarModalContent ref='varModal' {...{
            type: 'single',
            variableType
          }
           } />
        </Modal>
        <div ref='editPoint' />
      </div>
    )
  }
}

export default PointActions
